package com.unm.config;

import java.io.BufferedReader;
import java.io.Reader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import oracle.sql.CLOB;

import org.json.JSONObject;
import com.unm.core.IHandler;

public class LogicFun  extends IHandler {
	public LogicFun() {
	}
	public void doAction(java.sql.Connection con, HttpServletRequest req) throws Exception {
		String func = req.getAttribute("__Func").toString();
		
		System.out.println("<func>"+func);
		
		if(func.equalsIgnoreCase("actionsplitcolumn"))
		{
			JSONObject data = (JSONObject)req.getAttribute("__data");
			if(data!=null)
			{
				String cfg = data.getString("cfg");//此处是取得数据库的cfg字段数据
				JSONObject tt = new JSONObject(cfg);
				for (Iterator iter = tt.keys(); iter.hasNext();) { 
			        String key = (String)iter.next();
			        data.put(key, tt.getString(key));
				}
				data.put("cfg", "");
			}
			req.setAttribute("__data", data);
		}
		if(func.equalsIgnoreCase("actionsumcolumn"))
		{
			JSONObject Jcfg = (JSONObject)req.getAttribute("__cfg");
			String init = Jcfg.getString("init");//
			JSONObject JData = (JSONObject)req.getAttribute("__data");			
			if(JData!=null)
			{
				String tline = "";
				String[] arInit=init.split(",");
		        for(int i=0;i<arInit.length;i++)
		        {
		        	String tmp = arInit[i];
		        	String[] array2=tmp.split("#"); 
		        	tline+=","+array2[0]+":\""+JData.getString(array2[1])+"\"";
		        }
		        if(tline.length()>0) tline = tline.substring(1);
		        JData.put("cfg", "{"+tline+"}");
			}
			req.setAttribute("__data", JData);
		}
		
		if(func.equalsIgnoreCase("actiongetclob"))
		{
			JSONObject JData = (JSONObject)req.getAttribute("__data");	
			int id = JData.getInt("id");
			String sql = "select main from u_action1 where  id=?";
			PreparedStatement pstmt = con.prepareStatement(sql);
            pstmt.setInt(1,id );
	    	ResultSet dbr1 = pstmt.executeQuery();
	        if(dbr1.next())
	        {
				CLOB clob =  (oracle.sql.CLOB)dbr1.getClob("main");
	    		  if(clob!=null)
	    		  {
		      		  Reader is = clob.getCharacterStream();// 得到流
		      		  BufferedReader br = new BufferedReader(is);
		      		  String s = br.readLine();
		      		  StringBuffer sb = new StringBuffer();
		      		  while (s != null) {//执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
			      		 sb.append(s);
			      		 s = br.readLine();
		      		  }
		      		//System.out.println("<datalogic>"+sb.toString());
		      		JData.put("cfgcode",sb.toString());	
	    		  }
	        }
	        req.setAttribute("__data", JData);
		}
	}
}
